package com.laxcen.smoke.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.iot.model.v20180120.InvokeThingServiceRequest;
import com.aliyuncs.iot.model.v20180120.InvokeThingServiceResponse;
import com.aliyuncs.iot.model.v20180120.PubRequest;
import com.aliyuncs.iot.model.v20180120.PubResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.laxcen.smoke.config.CommonEnum;
import com.laxcen.smoke.dao.IssueDao;
import com.laxcen.smoke.dto.res.*;
import com.laxcen.smoke.entity.PickCode;
import com.laxcen.smoke.service.IssueService;
import com.laxcen.smoke.util.DBUtils;
import com.laxcen.smoke.util.IdUtils;
import com.laxcen.smoke.util.Response;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class IssueServiceImpl implements IssueService {

    @Autowired
    private IssueDao issueDao;

    @Value("${accessKey}")
    private String accessKey;

    @Value("${accessSecret}")
    private String accessSecret;

    @Value("${serviceip}")
    private String serviceip;

    @Value("${productkey}")
    private String productkey;

    @Override
    public Response insert(String versionno, String versiondes, MultipartFile file) {

        String repeatid = issueDao.getIdByVerNo(versionno);
        if (repeatid!=null){
            return new Response(CommonEnum.VERSION_IS_EXIST);
        }

            if (!file.isEmpty()) {
                String fileName = file.getOriginalFilename();  // 文件名
                String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
                String filePath = "shiro-core/src/main/resources/webapp/uploadapk/"; // 上传后的路径
                fileName = IdUtils.createIdbyUUID() + suffixName; // 新文件名
                File dest = new File(filePath+fileName);

                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                //构建真实的文件路径
                File newFile = new File(dest.getAbsolutePath() + File.separator);
                try {
                    file.transferTo(newFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                    issueDao.insert(String.valueOf( DBUtils.nextId()), versionno, versiondes, "http://"+serviceip+":8080/uploadapk/" + fileName, new Date());

            }else {
                return new Response(CommonEnum.FILE_IS_NULL);
            }


        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response update(String id, String versionno, String versiondes, MultipartFile file) {
        //查询当前版本号的id
        String exitsid = issueDao.getIdByVerNo(versionno);
        if (exitsid!=null) {
            if (!id.equals(exitsid)) {
                return new Response(CommonEnum.VERSION_IS_EXIST);
            }
        }
        String existfile = issueDao.getFileById(id);
        String existdes = issueDao.getVersionDesById(id);
        //如果不传文件保留文件为默认
        if (null==file||"".equals(file)){
            if (versiondes==null||"".equals(versiondes)) {
                //如果不传版本描述保留描述为默认
                issueDao.updateVersion(versionno, existdes, existfile, id);
            }else {
                issueDao.updateVersion(versionno, versiondes, existfile, id);
            }
        }else{
            String fileName = file.getOriginalFilename();  // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
            String filePath = "shiro-core/src/main/resources/webapp/uploadapk/"; // 上传后的路径
            fileName = IdUtils.createIdbyUUID() + suffixName; // 新文件名
            File dest = new File(filePath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            //构建真实的文件路径
            File newFile = new File(dest.getAbsolutePath() + File.separator);
            try {
                file.transferTo(newFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (versiondes==null||"".equals(versiondes)) {
                issueDao.updateVersion(versionno, existdes, "http://"+serviceip+":8080/uploadapk/" + fileName, id);
            }else {
                issueDao.updateVersion(versionno, versiondes, "http://"+serviceip+":8080/uploadapk/" + fileName, id);
            }
        }
//        else {
//            return new Response(CommonEnum.FILE_IS_NULL);
//        }
        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response delete(String id) {

        issueDao.deleteOne(id);
        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response<PageInfo<AppManageListRes>> getListAll(int pageNo, int pageSize) {
        Page page = PageHelper.startPage(pageNo,pageSize);
        List<AppManageListRes> list = issueDao.getListAll();
        Response<PageInfo<AppManageListRes>> response = new Response<>();
        PageInfo pageInfo = page.toPageInfo();
        pageInfo.setList(list);
        response.setOK();
        response.setData(pageInfo);
        return response;
    }

    @Override
    public Response<PageInfo<AppRecordRes>> getRecordList(int pageNo, int pageSize) {
        Page page = PageHelper.startPage(pageNo,pageSize);
        List<AppRecordRes> list = issueDao.getAppRecordList();
        Response<PageInfo<AppRecordRes>> response = new Response<>();
        PageInfo pageInfo = page.toPageInfo();
        pageInfo.setList(list);
        response.setOK();
        response.setData(pageInfo);
        return response;
    }

    @Override
    public Response<PageInfo<AppStatusRes>> getStatusList(int pageNo, int pageSize) {
        Page page = PageHelper.startPage(pageNo,pageSize);
        List<AppStatusRes> list = issueDao.getAppStatusList();
        Response<PageInfo<AppStatusRes>> response = new Response<>();
        PageInfo pageInfo = page.toPageInfo();
        pageInfo.setList(list);
        response.setOK();
        response.setData(pageInfo);
        return response;
    }

    @Override
    public Response<PageInfo<AppManageListRes>> getListByTab(String starttime, String endtime, int pageNo, int pageSize) throws ParseException {
        Page page = PageHelper.startPage(pageNo,pageSize);
        List<AppManageListRes> list = new LinkedList<>();
        if ("".equals(starttime)&&"".equals(endtime)) {
            list = issueDao.getListAll();
        }else if (starttime==null&&endtime==null){
            list = issueDao.getListAll();
        }else if (!"".equals(starttime)&&!"".equals(endtime)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
            Date datestart = sdf.parse(starttime);
            Date dateend = sdf.parse(endtime);
            list = issueDao.getListByTime(datestart,dateend);
        }else if (starttime!=null&&endtime!=null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
            Date datestart = sdf.parse(starttime);
            Date dateend = sdf.parse(endtime);
            list = issueDao.getListByTime(datestart,dateend);
        }
        Response<PageInfo<AppManageListRes>> response = new Response<>();
        PageInfo pageInfo = page.toPageInfo();
        pageInfo.setList(list);
        response.setOK();
        response.setData(pageInfo);
        return response;
    }

    @Override
    public Response upGradeOne(String smartno, String versionno,int issueway,String issuetime) {
        String versionid = issueDao.getIdByVerNo(versionno);
        if (versionid==null){
            return new Response(CommonEnum.VERSION_IS_NOT_EXIST);
        }
        Response responses = new Response();

        //1表示定时下发 0表示立即下发
        if (1==issueway){
            Timer t = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    System.out.println("开始执行定时下发");
                    //添加到升级记录表
                    issueDao.insertIssueRecord(String.valueOf( DBUtils.nextId()),smartno,versionno,new Date());
//                    String devicename = issueDao.getDeviceName(smartno);
                    String apkurl = issueDao.getFileUrlById(versionid);
                    //升级下发到iot服务  参数 智能柜编号，版本号，apk路径(物模型服务未建)
                    IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
                    DefaultAcsClient client = new DefaultAcsClient(profile);
                    InvokeThingServiceRequest request = new InvokeThingServiceRequest();
                    String param = "{\"DeviceNo\":\""+smartno+"\",\"VersionNo\":\""+versionno+"\",\"ApkUrl\":\""+apkurl+"\"}";
                    request.setArgs(param);
                    request.setIdentifier("APPUpdateGrade");
                    request.setProductKey(productkey);
                    request.setDeviceName(smartno);
                    try
                    {
                        InvokeThingServiceResponse response = client.getAcsResponse(request);
                        //比较版本号
                        if (versionno.equals(issueDao.getVersionnoBySmNo(smartno))){
                            if (null==issueDao.getIssueSmNoBYNo(smartno)) {
                                //插入到升级状态表(成功)
                                issueDao.insertIssueStatus(String.valueOf(DBUtils.nextId()), smartno,versionno,issueDao.getVersionnoBySmNo(smartno), 1, new Date());
                            }else {
                                //更新到升级状态表(成功)
                                issueDao.updateIssueStatus( 1,versionno,issueDao.getVersionnoBySmNo(smartno), smartno);
                            }
                        }else {
                            if (null==issueDao.getIssueSmNoBYNo(smartno)) {
                                //插入到升级状态表(失败)
                                issueDao.insertIssueStatus(String.valueOf(DBUtils.nextId()), smartno,versionno,issueDao.getVersionnoBySmNo(smartno), 2, new Date());
                            }else {
                                //更新到升级状态表(失败)
                                issueDao.updateIssueStatus( 2,versionno,issueDao.getVersionnoBySmNo(smartno), smartno);
                            }
                        }

                        if (null!=response.getData().getResult()) {
                            issueDao.updateSmartVerOne(versionid,smartno);
                            String result = response.getData().getResult();
                            JSONObject json = JSONObject.fromObject(result);
                            String message = json.getString("ErrorMessage");
//                        if (response.getSuccess()==false){
//                            responses.setMsg("远程升级失败");
                            responses.setData(message);
                            responses.setOK();
                        }else {
                            responses.setData(response.getErrorMessage());
                            responses.setError(600);
                        }
//                                return responses;
//                        }
                    }
                    catch (ServerException e)
                    {
                        e.printStackTrace();
                    }
                    catch (ClientException e)
                    {
                        e.printStackTrace();
                    }
                }

            };
            String year = issuetime.substring(0,4);
            String month = issuetime.substring(5,7);
            String day = issuetime.substring(8,10);
            String hour = issuetime.substring(11,13);
            String minu = issuetime.substring(14,16);
            String sec = issuetime.substring(17,19);
            Calendar c = Calendar.getInstance();
            c.set(Calendar.YEAR,Integer.valueOf(year));
            c.set(Calendar.MONTH,Integer.valueOf(month)-1);
            c.set(Calendar.DAY_OF_MONTH,Integer.valueOf(day));
            c.set(Calendar.HOUR_OF_DAY,Integer.valueOf(hour));
            c.set(Calendar.MINUTE,Integer.valueOf(minu));
            c.set(Calendar.SECOND,Integer.valueOf(sec));// 时间可以自己设置
            t.schedule(task, c.getTime());
            responses.setData("APP定时升级中");
            responses.setOK();
            return responses;


        }else if(0==issueway){
            //添加到升级记录表
            issueDao.insertIssueRecord(String.valueOf( DBUtils.nextId()),smartno,versionno,new Date());
            String apkurl = issueDao.getFileUrlById(versionid);
            //升级下发到iot服务  参数 智能柜编号，版本号，apk路径(物模型服务未建)
            IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            InvokeThingServiceRequest request = new InvokeThingServiceRequest();
            String param = "{\"DeviceNo\":\""+smartno+"\",\"VersionNo\":\""+versionno+"\",\"ApkUrl\":\""+apkurl+"\"}";
            request.setArgs(param);
            request.setIdentifier("APPUpdateGrade");
            request.setProductKey(productkey);
            request.setDeviceName(smartno);
            try
            {
                InvokeThingServiceResponse response = client.getAcsResponse(request);
                //比较版本号
                if (versionno.equals(issueDao.getVersionnoBySmNo(smartno))){
                    if (null==issueDao.getIssueSmNoBYNo(smartno)) {
                        //插入到升级状态表(成功)
                        issueDao.insertIssueStatus(String.valueOf(DBUtils.nextId()), smartno,versionno,issueDao.getVersionnoBySmNo(smartno), 1, new Date());
                    }else {
                        //更新到升级状态表(成功)
                        issueDao.updateIssueStatus( 1,versionno,issueDao.getVersionnoBySmNo(smartno), smartno);
                    }
                }else {
                    if (null==issueDao.getIssueSmNoBYNo(smartno)) {
                        //插入到升级状态表(失败)
                        issueDao.insertIssueStatus(String.valueOf(DBUtils.nextId()), smartno,versionno,issueDao.getVersionnoBySmNo(smartno), 2, new Date());
                    }else {
                        //更新到升级状态表(失败)
                        issueDao.updateIssueStatus( 2,versionno,issueDao.getVersionnoBySmNo(smartno), smartno);
                    }
                }
                if (null!=response.getData().getResult()) {
                    issueDao.updateSmartVerOne(versionid,smartno);
                    String result = response.getData().getResult();
                    JSONObject json = JSONObject.fromObject(result);
                    String message = json.getString("ErrorMessage");
//                if (response.getSuccess()==false){
//                    responses.setMsg("远程升级失败");
                    responses.setData(message);
                    responses.setOK();
                }else {
                    responses.setData(response.getErrorMessage());
                    responses.setError(600);
                }
                                return responses;
//                }
            }
            catch (ServerException e)
            {
                e.printStackTrace();
            }
            catch (ClientException e)
            {
                e.printStackTrace();
            }
        }


        return responses;
    }

    @Override
    public Response upGradeAll(String smartno, String versionno,int issueway,String issuetime) {
        String versionid = issueDao.getIdByVerNo(versionno);
        if (versionid==null){
            return new Response(CommonEnum.VERSION_IS_NOT_EXIST);
        }
        Response responses = new Response();

        //1表示定时下发 0表示立即下发
        if (1==issueway){
            Timer t = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    System.out.println("开始执行定时下发(全部)");
                    String apkurl = issueDao.getFileUrlById(versionid);
                    String[] smartnoall = smartno.split(",");
                    for (int i = 0;i < smartnoall.length;i++){
                        //添加到升级记录表
                        issueDao.insertIssueRecord(String.valueOf( DBUtils.nextId()),smartnoall[i],versionno,new Date());
//                        String devicename = issueDao.getDeviceName(smartnoall[i]);
                        //升级下发到iot服务  参数 智能柜编号，版本号，apk路径
                        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
                        DefaultAcsClient client = new DefaultAcsClient(profile);
                        InvokeThingServiceRequest request = new InvokeThingServiceRequest();
                        String param = "{\"DeviceNo\":\""+smartnoall[i]+"\",\"VersionNo\":\""+versionno+"\",\"ApkUrl\":\""+apkurl+"\"}";
                        request.setArgs(param);
                        request.setIdentifier("APPUpdateGrade");
                        request.setProductKey(productkey);
                        request.setDeviceName(smartnoall[i]);
                        try
                        {
                            InvokeThingServiceResponse response = client.getAcsResponse(request);
                            //比较版本号
                            if (versionno.equals(issueDao.getVersionnoBySmNo(smartnoall[i]))){
                                if (null==issueDao.getIssueSmNoBYNo(smartnoall[i])) {
                                    //插入到升级状态表(成功)
                                    issueDao.insertIssueStatus(String.valueOf(DBUtils.nextId()), smartnoall[i],versionno,issueDao.getVersionnoBySmNo(smartnoall[i]), 1, new Date());
                                }else {
                                    //更新到升级状态表(成功)
                                    issueDao.updateIssueStatus( 1,versionno,issueDao.getVersionnoBySmNo(smartnoall[i]), smartnoall[i]);
                                }
                            }else {
                                if (null==issueDao.getIssueSmNoBYNo(smartnoall[i])) {
                                    //插入到升级状态表(失败)
                                    issueDao.insertIssueStatus(String.valueOf(DBUtils.nextId()), smartnoall[i], versionno,issueDao.getVersionnoBySmNo(smartnoall[i]),2, new Date());
                                }else {
                                    //更新到升级状态表(失败)
                                    issueDao.updateIssueStatus( 2,versionno,issueDao.getVersionnoBySmNo(smartnoall[i]), smartnoall[i]);
                                }
                            }
                            if (null!=response.getData().getResult()) {
                               issueDao.updateSmartVerOne(versionid,smartnoall[i]);
                               String result = response.getData().getResult();
                               JSONObject json = JSONObject.fromObject(result);
                               String message = json.getString("ErrorMessage");
//                            if (response.getSuccess()==false){
//                                responses.setMsg("远程升级失败");
                               responses.setData(message);
                               responses.setOK();
                           }else {
                               responses.setData(response.getErrorMessage());
                               responses.setError(201);
                           }
//                            }
                        }
                        catch (ServerException e)
                        {
                            e.printStackTrace();
                        }
                        catch (ClientException e)
                        {
                            e.printStackTrace();
                        }
                    }
                }
            };
            String year = issuetime.substring(0,4);
            String month = issuetime.substring(5,7);
            String day = issuetime.substring(8,10);
            String hour = issuetime.substring(11,13);
            String minu = issuetime.substring(14,16);
            String sec = issuetime.substring(17,19);
            Calendar c = Calendar.getInstance();
            c.set(Calendar.YEAR,Integer.valueOf(year));
            c.set(Calendar.MONTH,Integer.valueOf(month)-1);
            c.set(Calendar.DAY_OF_MONTH,Integer.valueOf(day));
            c.set(Calendar.HOUR_OF_DAY,Integer.valueOf(hour));
            c.set(Calendar.MINUTE,Integer.valueOf(minu));
            c.set(Calendar.SECOND,Integer.valueOf(sec));// 时间可以自己设置
            t.schedule(task, c.getTime());
            responses.setData("APP定时升级中");
            responses.setOK();
            return responses;


        }else if (0==issueway){
            String apkurl = issueDao.getFileUrlById(versionid);
            String[] smartnoall = smartno.split(",");
            for (int i = 0;i < smartnoall.length;i++){
                //添加到升级记录表
                issueDao.insertIssueRecord(String.valueOf( DBUtils.nextId()),smartnoall[i],versionno,new Date());
                //升级下发到iot服务  参数 智能柜编号，版本号，apk路径
//                String devicename = issueDao.getDeviceName(smartnoall[i]);
                IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
                DefaultAcsClient client = new DefaultAcsClient(profile);
                InvokeThingServiceRequest request = new InvokeThingServiceRequest();
                String param = "{\"DeviceNo\":\""+smartnoall[i]+"\",\"VersionNo\":\""+versionno+"\",\"ApkUrl\":\""+apkurl+"\"}";
                request.setArgs(param);
                request.setIdentifier("APPUpdateGrade");
                request.setProductKey(productkey);
                request.setDeviceName(smartnoall[i]);
                try
                {
                    InvokeThingServiceResponse response = client.getAcsResponse(request);
//比较版本号
                    if (versionno.equals(issueDao.getVersionnoBySmNo(smartnoall[i]))){
                        if (null==issueDao.getIssueSmNoBYNo(smartnoall[i])) {
                            //插入到升级状态表(成功)
                            issueDao.insertIssueStatus(String.valueOf(DBUtils.nextId()), smartnoall[i],versionno,issueDao.getVersionnoBySmNo(smartnoall[i]), 1, new Date());
                        }else {
                            //更新到升级状态表(成功)
                            issueDao.updateIssueStatus( 1,versionno,issueDao.getVersionnoBySmNo(smartnoall[i]), smartnoall[i]);
                        }
                    }else {
                        if (null==issueDao.getIssueSmNoBYNo(smartnoall[i])) {
                            //插入到升级状态表(失败)
                            issueDao.insertIssueStatus(String.valueOf(DBUtils.nextId()), smartnoall[i],versionno,issueDao.getVersionnoBySmNo(smartnoall[i]), 2, new Date());
                        }else {
                            //更新到升级状态表(失败)
                            issueDao.updateIssueStatus( 2,versionno,issueDao.getVersionnoBySmNo(smartnoall[i]), smartnoall[i]);
                        }
                    }
                    if (null!=response.getData().getResult()) {
                        issueDao.updateSmartVerOne(versionid,smartnoall[i]);
                        String result = response.getData().getResult();
                        JSONObject json = JSONObject.fromObject(result);
                        String message = json.getString("ErrorMessage");
//                    if (response.getSuccess()==false){
//                        responses.setMsg("在线升级失败");
                        responses.setData(message);
                        responses.setOK();
                    }else {
                        responses.setData(response.getErrorMessage());
                        responses.setError(600);
                    }
//                        return responses;
//                    }
                }
                catch (ServerException e)
                {
                    e.printStackTrace();
                }
                catch (ClientException e)
                {
                    e.printStackTrace();
                }
            }
        }


        return responses;
    }

    @Override
    public Response<PageInfo<AppUpGradeListRes>> getAppUpGradeAllList(int pageNo, int pageSize) {
        Page page = PageHelper.startPage(pageNo, pageSize);
        List<AppUpGradeListRes> list = issueDao.getAppUpGradeAllList();
        Response<PageInfo<AppUpGradeListRes>> response = new Response<>();
        PageInfo pageInfo = page.toPageInfo();
        pageInfo.setList(list);
        response.setOK();
        response.setData(pageInfo);
        return response;
    }

    @Override
    public Response<PageInfo<AppUpGradeListRes>> getAppUpGradeListByTab(String versionno, String starttime, String endtime, int pageNo, int pageSize) throws ParseException {
        Page page = PageHelper.startPage(pageNo,pageSize);
        List<AppUpGradeListRes> list = new LinkedList<>();
        if ("".equals(versionno)&&"".equals(starttime)&&"".equals(endtime)) {
            list = issueDao.getAppUpGradeAllList();
        }else if (!"".equals(versionno)&&"".equals(starttime)&&"".equals(endtime)) {
            list = issueDao.getAppUpGradeListByVerNo(versionno);
        }else if ("".equals(versionno)&&!"".equals(starttime)&&!"".equals(endtime)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
            Date datestart = sdf.parse(starttime);
            Date dateend = sdf.parse(endtime);
            list = issueDao.getAppUpGradeListByTime(datestart,dateend);
        } else if (versionno==null&&starttime==null&&endtime==null){
            list = issueDao.getAppUpGradeAllList();
        }else if (!"".equals(versionno)&&!"".equals(starttime)&&!"".equals(endtime)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date datestart = sdf.parse(starttime);
            Date dateend = sdf.parse(endtime);
            list = issueDao.getAppUpGradeListByVerNoAndTime(versionno,datestart, dateend);
        }else if (versionno!=null&&starttime==null&&endtime==null){
            list = issueDao.getAppUpGradeListByVerNo(versionno);
        }else if (versionno==null&&starttime!=null&&endtime!=null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
            Date datestart = sdf.parse(starttime);
            Date dateend = sdf.parse(endtime);
            list = issueDao.getAppUpGradeListByTime(datestart,dateend);
        }else if (versionno!=null&&starttime!=null&&endtime!=null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd") ;
            Date datestart = sdf.parse(starttime);
            Date dateend = sdf.parse(endtime);
            list = issueDao.getAppUpGradeListByVerNoAndTime(versionno,datestart, dateend);
        }
        Response<PageInfo<AppUpGradeListRes>> response = new Response<>();
        PageInfo pageInfo = page.toPageInfo();
        pageInfo.setList(list);
        response.setOK();
        response.setData(pageInfo);
        return response;
    }

    @Override
    public Response verify(int verifynum, double verifymovetime) {
        List<String> list = issueDao.getSmartNo();
        for (int i = 0 ;i < list.size(); i++){
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);

        PubRequest request = new PubRequest();
        request.setProductKey(productkey);
        String param = "{\"params\":{\"VerifyNum\":\"" + verifynum + "\",\"VerifyMoveTime\":\"" + verifymovetime + "\"},\"method\":\"thing.event.VerifyCode.post\"}";
        request.setMessageContent(Base64.encodeBase64String(param.getBytes()));
        request.setTopicFullName("/sys/"+productkey+"/" + list.get(i) + "/thing/event/VerifyCode/post");

        issueDao.insertpickcode(String.valueOf(DBUtils.nextId()), verifynum, verifymovetime, new Date());
        try {
            PubResponse response = client.getAcsResponse(request);
//            PubResponse response = client.getAcsResponse(request);
            if (response.getSuccess() == false) {
                Response response1 = new Response();
                response1.setMsg("事件上报失败");
                response1.setData(response.getErrorMessage());
                return response1;
            }
//            System.out.println(response.getData().getResult());
//            System.out.println(response.getSuccess());
//            System.out.println(response.getErrorMessage());
            Response responses = new Response();
            responses.setOK();
            return responses;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
        Response response = new Response();
        response.setOK();
        return  response;
    }

    @Override
    public Response setpassword(String smartno, String password,int roleflag,String province,String city,String area) {
        if (roleflag==0) {
            issueDao.updateSmartpassword(password, new Date(), smartno);
        }else if (roleflag==1) {
            String place = null;
            if (!province.isEmpty()){
                place = province;
            }
            if (!city.isEmpty()){
                place =place+"/"+ city;
            }
            if (!area.isEmpty()){
                place = place+"/"+area;
            }
            issueDao.updateSmartpasswordRole(password, new Date(), smartno, place);
        }
        //获取设备编号用于监听事件轮询
        List<String> list = issueDao.getSmartNo();
        for (int i = 0; i < list.size(); i++){
            IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", "LTAI5tQqhoe1XSrkoCWkDDQ9", "MXycRe3SmNlDPKuLNt1cfxhFyjk5Cf");
            DefaultAcsClient client = new DefaultAcsClient(profile);
            InvokeThingServiceRequest request = new InvokeThingServiceRequest();
            String param = "{\"MessageId\":\""+DBUtils.nextId()+"\",\"DeviceNo\":\""+smartno+"\",\"Pwd\":\""+password+"\"}";
            request.setArgs(param);
            request.setIdentifier("UpdatePwd");
            request.setProductKey(productkey);
            request.setDeviceName(list.get(i));
            try {
                InvokeThingServiceResponse response = client.getAcsResponse(request);
            } catch (ServerException e) {
                e.printStackTrace();
            } catch (ClientException e) {
                e.printStackTrace();
            }
        }

        Response response = new Response();
        response.setOK();
        return response;
    }


    @Override
    public Response<PageInfo<SmartPasswordRes>> getsmartpasswordlist(int pageNo, int pageSize, int roleflag, String province, String city, String area) {
        Page page = PageHelper.startPage(pageNo,pageSize);
        List<SmartPasswordRes> list = new LinkedList<>();
        if (roleflag==0) {
            list = issueDao.getSmartPasswordList();
        }else if (roleflag == 1){
            String place = null;
            if (!province.isEmpty()){
                place = province;
            }
            if (!city.isEmpty()){
                place =place+"/"+ city;
            }
            if (!area.isEmpty()){
                place = place+"/"+area;
            }
            list = issueDao.getSmartPasswordListRole(place);
        }
        Response<PageInfo<SmartPasswordRes>> response = new Response<>();
        PageInfo pageInfo = page.toPageInfo();
        pageInfo.setList(list);
        response.setOK();
        response.setData(pageInfo);
        return response;
    }

    @Override
    public Response<PageInfo<PickCode>> getVerifyList(int pageNo, int pageSize) {

        Page page = PageHelper.startPage(pageNo, pageSize);
        List<PickCode> list = issueDao.getPickCodeList();
        PageInfo pageInfo = page.toPageInfo();
        pageInfo.setList(list);
        Response<PageInfo<PickCode>> response = new Response<>();
        response.setOK();
        response.setData(pageInfo);
        return response;
    }



}
